<!--
 * @Author: 梁 卓
 * @Version: V1.0.0
 * @Date: 2024-02-18 16:38:53
 * @LastEditors: 梁 卓
 * @LastEditTime: 2024-02-19 17:16:52
 * @FilePath: PriceIndice.vue
 * Copyright 2024 Marvin, All Rights Reserved. 
 * 2024-02-18 16:38:53
 * @Description: 
-->
<template>
  <div>
    <div class="b_item">
      <el-row>
        <el-col :span="12">
          <el-button class="select_buttom" :class="{active: isChose}" @click="weekClickEvent">周数据</el-button>
        </el-col>
        <el-col :span="12">
          <el-button class="select_buttom" :class="{active: !isChose}" @click="monthClickEvent">月数据</el-button>
        </el-col>
      </el-row>
    </div>
    <div class="c_item" v-for="(item, index) in parentNameArr" :key="index">
      <div class="t_item">
        <el-row :gutter="20">
          <el-col :span="5" style="font-size: 20px; font-weight: bold;">{{ item }}价格详情（元/斤）</el-col>
        </el-row>
      </div>
      <div class="l_item" v-loading="lodding_l">
        <div style="border-bottom: 1px solid #ccc ;">
          <el-row   style="font-size: 18px; font-weight: bold; color: rgb(45, 42, 42);">
            <el-col :span="6" >名称</el-col>
            <el-col :span="6" >{{ titlePirce }}</el-col>
            <el-col :span="6" >环比(%)</el-col>
            <el-col :span="6" >同比(%)</el-col>
          </el-row>
        </div>
        <div class="price_info" v-for="(item, index_1) in priceInfoArr[index]" :key="index_1">
          <el-row style="height: 50px;">
            <el-col :span="6" >{{ item.productName }}</el-col>
            <el-col :span="6" >{{ item.thisData }}</el-col>
            <el-col :span="6" >{{ item.monthRatio }}</el-col>
            <el-col :span="6" >{{ item.yearRatio }}</el-col>
          </el-row>
        </div>
      </div>
      <div class="r_item"  v-loading="lodding_r">
        <div class="chart_box" id="echartRef" ref="echartRef"></div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import {lastWeekProductPrice, recentlyFiveWeekAveragePrice,
  lastMonthProductPrice, recentlyFiveMonthAveragePrice} from '@/api/priceIndice'
export default {
  name: 'priceIndice',

  data() {
    return {
      parentNameArr: [],
      priceInfoArr: [],
      series: [],
      xAxis: [],
      legend: [],
      isChose: true,
      lodding_l: true,
      lodding_r: true,
      titlePirce: '上周均价'
    };
  },
  created() {
    this.lastWeek()
    this.recentlyFiveWeek()
    
  },
  // 必须使用，不然无法获得dom
  updated() {
    this.$nextTick(()=>{
      this.initEcharts(this.legend,this.xAxis,this.series)
    })
  },

  methods: {
    // 对object中key排序
    sortDataByName(data) {
      const sortedData = {};
      const keys = Object.keys(data).sort();
      for (const key of keys) {
        sortedData[key] = data[key];
      }
      return sortedData;
    },
    f1(objectData) {
      this.reset1()
      const sortedData = this.sortDataByName(objectData)
        for(let key in sortedData) {
          this.parentNameArr.push(key)
          let pArr = []
          objectData[key].forEach(item => {
            pArr.push(item)
          })
          this.priceInfoArr.push(pArr)
        }
    },
    f2(objectData) {
      this.reset2()
      const sortedData = this.sortDataByName(objectData)
        for(let key in sortedData) {
          this.xAxis.push(sortedData[key]['xaxis'])
          this.legend.push(sortedData[key]['legend'])
          // 处理series
          var partSeries = []
          sortedData[key]['series'].forEach((item, index) => {
            let tmpSeries = {
              name: sortedData[key]['legend'][index],
              type: 'line',
              stack: 'Total',
              data: item
            }
            partSeries.push(tmpSeries)
          })
          this.series.push(partSeries)
        }
      this.$nextTick(()=>{
        this.initEcharts(this.legend,this.xAxis,this.series)
      })
    },
    lastWeek() {
      lastWeekProductPrice().then(res =>{
        this.lodding_l = true
        this.f1(res.data)
        this.titlePirce = '上周均价'
        this.lodding_l = false
      })
    },
    recentlyFiveWeek() {
      recentlyFiveWeekAveragePrice().then(res =>{
        this.lodding_r = true
        this.f2(res.data)
        this.lodding_r = false
      })
    },
    lastMonth() {
      lastMonthProductPrice().then(res =>{
        this.lodding_l = true
        this.f1(res.data)
        this.titlePirce = '上月均价'
        this.lodding_l = false
      })
    },
    recentlyFiveMonth() {
      recentlyFiveMonthAveragePrice().then(res =>{
        this.lodding_r = true
        this.f2(res.data)
        this.lodding_r = false
      })
    },
    initEcharts(legend,xAxis,series) {
      this.$refs.echartRef.forEach((item, index) => {
        var myChart = echarts.init(item);
        // myChart.clear()
        var option = {
          title: {
            subtext: '产品均价(元/斤)',
            left: 20,
            fontsize: 15,
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: legend[index]
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          toolbox: {
            feature: {
              saveAsImage: {}
            }
          },
          xAxis: {
            type: 'category',
            name: "日期",
            nameLocation: "end",
            data: xAxis[index],
            axisLabel: {
              fontSize: 11,
              fontStyle: "italic",
              interval: 0, //使x轴文字显示全
              // 使用formatter 换行显示
              formatter: function (params) {
                var newParamsName = "";
                var paramsNameNumber = params.length;
                var provideNumber = 11; //一行显示几个字
                var rowNumber = Math.ceil(paramsNameNumber / provideNumber);
                if (paramsNameNumber > provideNumber) {
                  for (var p = 0; p < rowNumber; p++) {
                    var tempStr = "";
                    var start = p * provideNumber;
                    var end = start + provideNumber;
                    if (p == rowNumber - 1) {
                      tempStr = params.substring(start, paramsNameNumber);
                    } else {
                      tempStr = params.substring(start, end) + "\n";
                    }
                    newParamsName += tempStr;
                  }
                } else {
                  newParamsName = params;
                }
                return newParamsName;
              },
            },
          },
          yAxis: {
            type: 'value'
          },
          series: series[index]
        }
        myChart.setOption(option);
        window.addEventListener("resize", function () {
          //监听窗口变动实时渲染
          myChart.resize();
        });
      })
      
    },
    weekClickEvent() {
      this.lastWeek()
      this.recentlyFiveWeek()
      this.isChose = true
    },
    monthClickEvent() {
      this.lastMonth()
      this.recentlyFiveMonth()
      this.isChose = false
    },
    reset1() {
      this.parentNameArr = []
      this.priceInfoArr = []
    },
    reset2() {
      this.series = []
      this.xAxis = []
      this.legend = []
    }
  },
};
</script>

<style lang="scss" scoped>
.b_item {
  width: 90%;
  margin: 5px 5%;
  padding: 5px;
}
.c_item {
  width: 90%;
  height: 400px;
  margin: 20px 5%;
  padding: 5px;
  border: 2px solid green;
  border-radius: 10px;
}
.t_item {
  width: 100%;
  height: 50px;
}
.l_item {
  float: left;
  width: 40%;
  height: 350px;
  // background-color: antiquewhite;
}
.r_item {
  float: right;
  width: 60%;
  height: 350px;
  // background-color: rgb(47, 190, 34);
}
.price_info {
  width: 100%;
  height: 50px;
  margin: 10px 0;
  border-bottom: 1px solid #ccc ;
  // background-color: blueviolet;
}
.chart_box {
  width: 100%;
  height: 100%;
}
.el-col {
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 40px;
}
.select_buttom {
  width: 100%;
  background-color: 	#fcfbfb;
  font-size: 17px;
  font-weight: bold;
  border-radius: 10px;
}

button:hover {
  background: #2adbb8;
  background-color: #2adbb8;
  color: #000;
  cursor: pointer;
}
button.active {
  background-color: #2abc9c;
  color: #000;
}
</style>